<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2021/2/1
 * Time: 14:33
 */

namespace app\api\controller;


use app\api\model\user\BalanceLog;
use app\common\exception\BaseException;
use app\common\mysic\profitShare\procedures\ProfitShare;
use app\factory\MqFactory;
use think\Console;
use think\Db;
use think\Exception;
use think\Request;

class Fix
{
    protected $args = [];
    public function __construct()
    {
        $args = (Request::instance())->server()['argv'];
        $ref = new \ReflectionClass(Fix::class);
        $refMethods = $ref->getMethods();
        $apiMethodNames = [];
        foreach($refMethods as $method) {
            if($method->name == '__construct') {
                continue;
            }
            $apiMethodNames[] = 'api/fix/' . strtolower($method->name);
        }
        if('index.php' != $args[0]) {
            echo 'parameter 1 must be index.php';
            exit;
        }
        if(!in_array(strtolower($args[1]), $apiMethodNames)) {
            echo 'method: ' . $args[1] . ' not exist';
            exit;
        }
        unset($args[0], $args[1]);
        $this->args = array_values($args);
    }

    public function fixUnexpectedFinishedBonus()
    {
        if(!in_array('issue', $this->args)) {
            echo "parameter 'issue (integer)' is required!\n";
            exit;
        }
        $issueKey = array_search('issue', $this->args);
        if(!key_exists($issueKey + 1, $this->args)) {
            exit("value of parameter 'issue' can't be null\n");
        }
        $issue = $this->args[$issueKey + 1];
        if(empty($issue)) {
            echo "value of parameter 'issue'  can't be zero!\n";
            exit;
        }
        if(!is_numeric($issue)) {
            echo "value of parameter 'issue'  is numeric!\n";
            exit;
        }

        if(!in_array('wxapp_id', $this->args)) {
            echo "parameter 'wxapp_id (integer)' is required!\n";
            exit;
        }
        $wxAppIdKey = array_search('wxapp_id', $this->args);
        if(!key_exists($wxAppIdKey + 1, $this->args)) {
            exit("value of parameter 'wxapp_id' can't be null\n");
        }
        $wxAppId = $this->args[$wxAppIdKey + 1];
        if(empty($wxAppId)) {
            echo "value of parameter 'wxapp_id'  can't be zero!\n";
            exit;
        }
        if(!is_numeric($wxAppId)) {
            echo "value of parameter 'wxapp_id'  is numeric!\n";
            exit;
        }
        $newIssue = db('wxapp_setting')->where('wxapp_id', $wxAppId)->value('periods_num');
        if(!$newIssue) {
            echo "wxapp setting periods_num is empty!\n";
            exit;
        }
        // 根据期号以及结束时间大于当前时间来筛选
        $receives = db('divide_receives')
            ->where('periods_num', $issue)
            ->where('wxapp_id', $wxAppId)
            ->where('finish_time', '>', \time())
            ->where('small_change', '>', 0)
            ->select();
        if(empty($receives)) {
            echo 'receives list not exist!';
            exit;
        }
        $receives = $receives->toArray();
        array_walk($receives ,function($receive)use ($newIssue){
            $receive['type'] = 0;
            $receive['periods_num'] = $newIssue;
            $receive['balance'] = $receive['small_change'];
            $receive['small_change'] = 0;
            Db::transaction(function() use ($receive){
                db('divide_receives')->where('receives_id', $receive['receives_id'])->update($receive);
                BalanceLog::add(50,  [
                    'user_id'  => $receive['user_id'],
                    'money'    => -$receive['balance'],
                    'wxapp_id' =>$receive['wxapp_id'],
                    'remark' => $receive['order_no'],
                ], ['order_no' => $receive['order_no']]);
                db('user')->where('user_id', $receive['user_id'])->update(['balance' => Db::raw('balance-' . $receive['balance'])]);
            });
        });

    }

    public function fixAgentProfit()
    {
        if(!in_array('start_time', $this->args)) {
            echo "parameter 'start_time (timestamp)' is required!\n";
            exit;
        }
        $startTimeKey = array_search('start_time', $this->args);
        if(!key_exists($startTimeKey + 1, $this->args)) {
            exit("value of parameter 'start_time' can't be null\n");
        }
        $startTimeValue = $this->args[$startTimeKey + 1];
        if(empty($startTimeValue)) {
            echo "value of parameter 'start_time'  can't be zero!\n";
            exit;
        }
        if(!is_numeric($startTimeValue)) {
            echo "value of parameter 'start_time'  is unix timestamp!\n";
            exit;
        }

        $systemProfitOrdersCount = db('divide_system')->where('create_time','>=', $startTimeValue)->where('status',1)->count();
        $currentPage = 1;
        $size = 50;
        $totalPage =  intval(ceil($systemProfitOrdersCount / $size));
        while($currentPage <= $totalPage) {
            echo '当前执行页: ' . $currentPage,PHP_EOL;
            echo '总页数: ' . $totalPage,PHP_EOL;
            $lastPageCount = $totalPage - $currentPage;
            echo '剩余页数: ' . $lastPageCount,PHP_EOL;
            $limit = ($currentPage - 1) * $size;
            $systemProfitOrders = db('divide_system')->where('create_time','>=', $startTimeValue)->where('status',1)->limit($limit, $size)->select()->all();
            foreach($systemProfitOrders as $systemProfitOrder) {
                $serviceProfitOrders = db('divide_service')->where('order_no', $systemProfitOrder['order_no'])->select()->all();

                $serviceOrderIdAgentIdMap = array_column($serviceProfitOrders, 'agent_id', 'id');

                $agents = db('agent')->whereIn('agent_id', implode(',',array_values($serviceOrderIdAgentIdMap)))->select()->all();
                $amount = [];

                foreach($agents as  $agent) {
                    if($agent['type'] == 3) {
                        continue;
                    }
                    $agentProfit = bcmul(
                        bcdiv(strval($agent['service_charge']),'100',2),
                        $systemProfitOrder['abonus'],
                        4
                    );
                    $amount[$agent['agent_id']] = $agentProfit;
                }
                switch(count($agents)) {
                    case 1:
                        $amount[$agents[0]['agent_id']] = bcmul(
                            bcdiv(strval($agents[0]['service_charge']),'100',2),
                            $systemProfitOrder['abonus'],
                            4
                        );
                        $agentsAmount = $amount[$agents[0]['agent_id']];
                        break;
                    case 2:
                        $amount[$agents[0]['agent_id']] = bcmul(
                            bcdiv(strval($agents[0]['service_charge'] - $agents[1]['service_charge']),'100',2),
                            $systemProfitOrder['abonus'],
                            4
                        );
                        $amount[$agents[1]['agent_id']] = bcmul(
                            bcdiv(strval($agents[1]['service_charge']),'100',2),
                            $systemProfitOrder['abonus'],
                            4
                        );
                        $agentsAmount = bcadd($amount[$agents[0]['agent_id']], $amount[$agents[1]['agent_id']], 4);
                        break;
                    case 3:
                        $amount[$agents[0]['agent_id']] = bcmul(
                            bcdiv(strval($agents[0]['service_charge'] - $agents[1]['service_charge']), '100', 2),
                            $systemProfitOrder['abonus'],
                            4
                        );
                        $amount[$agents[1]['agent_id']] = bcmul(
                            bcdiv(strval($agents[1]['service_charge'] - $agents[2]['service_charge']),'100',2),
                            $systemProfitOrder['abonus'],
                            4
                        );
                        $amount[$agents[2]['agent_id']] = bcmul(
                            bcdiv(strval($agents[2]['service_charge']),'100',2),
                            $systemProfitOrder['abonus'],
                            4
                        );
                        $agentsAmount = bcadd(bcadd($amount[$agents[0]['agent_id']], $amount[$agents[1]['agent_id']],4), $amount[$agents[2]['agent_id']], 4);
                        break;
                    default:
                        $agentsAmount = 0;
                }

                try {
                    foreach($serviceProfitOrders as $serviceProfitOrder) {
                        db('divide_service')->where('id', $serviceProfitOrder['id'])->update([
                            'amount' => $amount[$serviceOrderIdAgentIdMap[$serviceProfitOrder['id']]],
                            'update_time' => \time()
                        ]);
                    }

                    db('divide_system')->where('id', $systemProfitOrder['id'])->update([
                        'amount' => bcsub(strval($systemProfitOrder['abonus']), strval($agentsAmount), 4),
                        'update_time' => \time()
                    ]);
                } catch(\Exception $e) {
                    echo $e->getLine(),PHP_EOL;
                    echo $e->getMessage(),PHP_EOL;
                    echo '系统订单ID：' . $systemProfitOrder['id'],' : ' . $systemProfitOrder['order_no'],PHP_EOL;
                    echo '服务商订单分红: '. $systemProfitOrder['abonus'],PHP_EOL;
                    echo '代理分红总额: '. $agentsAmount,PHP_EOL;
                }
                echo '完成order号： ' . $systemProfitOrder['order_no'],PHP_EOL;

            }
            $currentPage++;
        }
    }

    public function profitSharing()
    {
        $msg = '{"order_no":"5059943584545633","receives_order_no":["SYSTEM_PROFIT_SHARING","5059943584545633","5039457977176711","5059661182697827","5057823648653133","5058169131930838"],"finish_profit_sharing":0}';
        $mq = MqFactory::instance();
        $mq->send($msg, 'new-share', 'profitsharing', 'profitsharing');
    }

    public function refund()
    {
        $msg = '{"orderNo":"5062843283902634","time":1616067572}';
        $mq = MqFactory::instance();
        $mq->send($msg, 'new-share', 'refund', 'refund');
    }

    public function dividend()
    {
        $msg = '{"orderId":25575,"time":1616471521}';
        $mq = MqFactory::instance();
        $mq->send($msg, 'userListData','userListDataLog','userListDataLog');
    }

    public function bonus()
    {
        $msg = '';
        $mq = MqFactory::instance();
        $mq->send($msg, 'merchant', 'bonus', 'bonus');
    }
}